<template>
    <div>
      <el-form size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
            <!-- 搜索框-->
         <el-form-item label="账号" prop="account">
                <el-input size="small" v-model="searchForm.account" placeholder="账号" clearable></el-input>
         </el-form-item>
         <el-form-item label="票码" prop="ticket">
            <el-select v-model="searchForm.ticket" filterable placeholder="请填写票码" style="width:100%;" >
              <el-option v-for="item in tickets" :label="item.organization" :value="item.organization" :key="item.id"></el-option>
            </el-select>
         </el-form-item>
         <el-form-item label="完成状态" prop="finishState">
            <el-select v-model="searchForm.finishState" placeholder="请填写完成状态" style="width:100%;" >
              <el-option v-for="item in finishStateArr" :label="item" :value="item" :key="item"></el-option>
            </el-select>
         </el-form-item>
         <el-form-item label="年" prop="createdate">
           <el-input-number v-model="createdate" controls-position="right" :min="2021" :max="9999"></el-input-number>
         </el-form-item>
         <el-form-item label="投票次数" prop="ticketCount">
           <el-input-number v-model="ticketCount" controls-position="right" :min="1" :max="9999"></el-input-number>
         </el-form-item>
         <el-form-item label="备注信息" prop="remarks">
                <el-input size="small" v-model="searchForm.remarks" placeholder="备注信息" clearable></el-input>
         </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="refreshList()" size="small">查询</el-button>
            <el-button @click="resetSearch()" size="small">重置</el-button>
          </el-form-item>
      </el-form>
        <!-- 导入导出-->
      <el-dialog  title="导入Excel" :visible.sync="isImportCollapse">
          <el-form size="small" :inline="true" v-show="isImportCollapse"  ref="importForm">
             <el-form-item>
              <el-button type="default" @click="downloadTpl()" size="small">下载模板</el-button>
             </el-form-item>
             <el-form-item prop="loginName">
                <el-upload
                  class="upload-demo"
                  :action="`${this.$http.BASE_URL}/peopleinformation/peopleassessaccount/peopleAssessAccount/import`"
                  :on-success="uploadSuccess"
                   :show-file-list="true">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只允许导入“xls”或“xlsx”格式文件！</div>
                </el-upload>
            </el-form-item>
          </el-form>
      </el-dialog>
      <div class="bg-white top">
      <el-row>
        <el-select size="small" v-model="ticket" filterable placeholder="请填写票类别" >
          <el-option v-for="item in tickets" :label="item.organization" :value="item.organization + ',' + item.code + ',' + item.organizationLevel" :key="item.id"></el-option>
        </el-select>
        <el-input-number size="small" v-model="count" controls-position="right" :min="1" :max="9999"></el-input-number>
        <el-button type="warning" size="small" icon="el-icon-edit-outline" @click="createCounts()" plain>生成考核账号</el-button>
         <el-date-picker
           v-model="checkTime.time"
           size="small"
           value-format="yyyy-MM-dd HH:mm:ss"
           type="datetime"
           placeholder="请填写考核日期">
         </el-date-picker>
        <el-button type="warning" size="small" icon="el-icon-edit-outline" @click="setCheckTime('start')" plain>设置考核时间</el-button>
        <el-button type="warning" size="small" icon="el-icon-edit-outline" @click="setCheckTime('over')" plain>结束考核</el-button>
        <!-- <el-button type="warning" size="small" icon="el-icon-edit-outline" @click="clearData()" plain>清除缓存</el-button> -->
        <!-- <el-button v-if="hasPermission('peopleinformation:peopleassessaccount:peopleAssessAccount:add')" type="primary" size="small" icon="el-icon-plus" @click="add()">新建</el-button> -->
        <!-- <el-button v-if="hasPermission('peopleinformation:peopleassessaccount:peopleAssessAccount:edit')" type="warning" size="small" icon="el-icon-edit-outline" @click="edit()"
         :disabled="dataListSelections.length != 1" plain>修改</el-button> -->
        <!-- <el-button v-if="hasPermission('peopleinformation:peopleassessaccount:peopleAssessAccount:del')" type="danger"   size="small" icon="el-icon-delete" @click="del()"
                  :disabled="dataListSelections.length <= 0" plain>删除
        </el-button> -->
        <el-button-group class="pull-right">
            <el-button v-if="hasPermission('peopleinformation:peopleassessaccount:peopleAssessAccount:import')" type="default" size="small" icon="el-icon-upload2" title="导入" @click="isImportCollapse = !isImportCollapse"></el-button>
            <el-button v-if="hasPermission('peopleinformation:peopleassessaccount:peopleAssessAccount:export')" type="default" size="small" icon="el-icon-download" title="导出" @click="exportExcel()"></el-button>
            <el-button
              type="default"
              size="small"
              icon="el-icon-refresh"
              @click="refreshList">
            </el-button>
        </el-button-group>
      </el-row>
    <el-table
      :data="dataList"
       size="small"
      @selection-change="selectionChangeHandle"
      @sort-change="sortChangeHandle"
      v-loading="loading"
      class="table">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
    <el-table-column
        prop="account"
        show-overflow-tooltip
        label="账号">
      </el-table-column>
    <el-table-column
        prop="ticket"
        show-overflow-tooltip
        label="票码">
      </el-table-column>
      <el-table-column
          prop="finishState"
          show-overflow-tooltip
          label="填写状态">
        </el-table-column>
    <el-table-column
        prop="remarks"
        show-overflow-tooltip
        label="备注信息">
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        fixed="right"
        :key="Math.random()"
        width="200"
        label="操作">
        <template  slot-scope="scope">
          <el-button v-if="hasPermission('peopleinformation:peopleassessaccount:peopleAssessAccount:view')" type="text" icon="el-icon-view" size="small" @click="view(scope.row.id)">查看</el-button>
          <el-button v-if="hasPermission('peopleinformation:peopleassessaccount:peopleAssessAccount:edit')" type="text" icon="el-icon-edit" size="small" @click="edit(scope.row.id)">修改</el-button>
          <!-- <el-button v-if="hasPermission('peopleinformation:peopleassessaccount:peopleAssessAccount:del')" type="text"  icon="el-icon-delete" size="small" @click="del(scope.row.id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageNo"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="total"
      background
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    </div>
    <asyn-for-tool ref='asynForTool' @returnData='returnData(arguments)'></asyn-for-tool>
        <!-- 弹窗, 新增 / 修改 -->
    <PeopleAssessAccountForm  ref="peopleAssessAccountForm" @refreshDataList="refreshList"></PeopleAssessAccountForm>
  </div>
</template>

<script>
  import PeopleAssessAccountForm from './PeopleAssessAccountForm'
  export default {
    data () {
      return {
        searchForm: {
          account: '',
          ticket: '',
          remarks: '',
          finishState: '',
          ticketCount: ''
        },
        checkTime: {
          time: ''
        },
        createdate: new Date().getFullYear(),
        ticketCount: 1,
        finishStateArr: ['未完成', '已完成'],
        permissions: '', // 账号权限
        count: 1,
        ticket: '',
        tickets: [],
        counts: [],
        dataList: [],
        createData: [],
        pageNo: 1,
        pageSize: 100,
        total: 0,
        orderBy: '',
        dataListSelections: [],
        isImportCollapse: false,
        loading: false,
        redisData: []
      }
    },
    components: {
      PeopleAssessAccountForm
    },
    activated () {
      this.refreshList()
    },
    watch: {
      createdate (newVal, oldVal) {
        if (this.createdate === '' || this.createdate === null || this.createdate === undefined || this.ticketCount === undefined || this.ticketCount === undefined || this.ticketCount === undefined) {
          this.searchForm.ticketCount = new Date().getFullYear() + '-' + 1
        } else {
          this.searchForm.ticketCount = this.createdate + '-' + this.ticketCount
        }
      },
      ticketCount (newVal, oldVal) {
        if (this.createdate === '' || this.createdate === null || this.createdate === undefined || this.ticketCount === undefined || this.ticketCount === undefined || this.ticketCount === undefined) {
          this.searchForm.ticketCount = new Date().getFullYear() + '-' + 1
        } else {
          this.searchForm.ticketCount = this.createdate + '-' + this.ticketCount
        }
      }
    },
    methods: {
      clearData () {
        this.$confirm('当前是否在考核完全结束后？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
              this.$http({
                url: '/peopleinformation/administrativelevel/peopleAdministrativeLevel/Redisclearall',
                method: 'get'
              }).then(({data}) => {
                alert("删除成功")
              })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.searchForm.ticketCount = ''
        if (this.createdate === '' || this.createdate === null || this.createdate === undefined || this.ticketCount === undefined || this.ticketCount === undefined || this.ticketCount === undefined) {
          this.searchForm.ticketCount = new Date().getFullYear() + '-' + 1
        } else {
          this.searchForm.ticketCount = this.createdate + '-' + this.ticketCount
        }
        this.$http({
          url: '/peopleinformation/peopleassessaccount/peopleAssessAccount/list',
          method: 'get',
          params: {
            'pageNo': this.pageNo,
            'pageSize': this.pageSize,
            'orderBy': this.orderBy,
            ...this.searchForm
          }
        }).then(({data}) => {
          if (data && data.success) {
            this.dataList = data.page.list
            this.total = data.page.count
            this.loading = false
            this.searchOneInstitutional()
          }
        })
      },
      // 设置考核时间
      setCheckTime (state) {
        this.$http({
          url: '/peopleinformation/checktime/checkTime/list',
          method: 'get',
          params: {
            'pageSize': 9999,
            'remarks': '人员'
          }
        }).then(({data}) => {
          if (data && data.success) {
            if (data.page.list[0] !== undefined) {
                var times = data.page.list[0].time
                if (state === 'start') {
                  if (this.checkTime.time !== '' && this.checkTime.time !== undefined) {
                    this.$http({
                      url: '/peopleinformation/administrativelevel/peopleAdministrativeLevel/Redisset',
                      method: 'post',
                      data: {
                        key: 'admintime',
                        value: this.checkTime.time + ',' + times
                      }
                    }).then(({data}) => {
                      if (data && data.success) {
                        alert("设置成功！")
                      }
                    })
                  } else {
                    alert("请设置考核时间！")
                  }
                } else if (state === 'over') {
                  this.checkTime.time = '4999-01-01 00:00:00'
                    this.$http({
                      url: '/peopleinformation/administrativelevel/peopleAdministrativeLevel/Redisset',
                      method: 'post',
                      data: {
                        key: 'admintime',
                        value: this.checkTime.time + ',' + times
                      }
                    }).then(({data}) => {
                      if (data && data.success) {
                        alert("考核结束！")
                        this.checkTime.time = ''
                      }
                    })
                }
             }
            }
          })
      },
      // 搜索框下拉数据提供 单位名称下拉框数据请求
      searchOneInstitutional () {
        this.$http({
          url: '/peopleinformation/organization/nameOfOrganization/treeData',
          method: 'get'
        }).then(({data}) => {
          this.tickets = []
          var datas = []
          this.tickets.push({
            id: '00',
            organization: '校领导',
            code: '00',
            organizationLevel: ' '
          },
          {
            id: '01',
            organization: '机关(同级)',
            code: '01',
            organizationLevel: ' '
          },
          {
            id: '02',
            organization: '教学教辅评机关(同级)',
            code: '02',
            organizationLevel: ' '
          },
          {
            id: '03',
            organization: '教辅(服务)',
            code: '03',
            organizationLevel: ' '
          },
          {
            id: '04',
            organization: '机关(服务)',
            code: '04',
            organizationLevel: ' '
          })
          for (var i in data.treeData) {
              datas.push(data.treeData[i])
          }
          this.tickets = this.tickets.concat(datas)
        })
      },
      // 考核账号弹窗
      createCountAlert (count) {
        if (this.tickets.length === 0) {
          this.$confirm(`当前票码未加载完全,请稍后几秒再试`, '提示', {
              confirmButtonText: '确定',
              showClose: false
            })
        } else {
          this.$confirm(`正在为您生成${count}个考核账号,请保持良好的网络等待大约${count}秒钟后点击确认否则会出现统计错误的情况!`, '提示', {
              confirmButtonText: '确定',
              showClose: false
            }).then(() => {
              this.refreshList()
            })
        }
      },
      // 账号权限判定并赋值
      isCountPermissions () {
        this.permissions = ''
        if (this.ticket.split(',')[0] === '校领导') {
          this.permissions = 'a7afcb2fb8924a5d845bd92606f2d4fd'
        } else if (this.ticket.split(',')[0] === '干部评班子(同级)') {
          this.permissions = 'cad6ebc4c316411da42016d24a342ddc'
        } else if (this.ticket.split(',')[0] === '教学教辅评机关(同级)') {
          this.permissions = '7d477d5bd3fb44e5a5d7a70290d88186'
        } else if (this.ticket.split(',')[0] === '机关(同级)') {
          this.permissions = '1ee9e3c899f1472d9c6ded52bde994bf'
        } else if (this.ticket.split(',')[0] === '教辅(服务)') {
          this.permissions = 'ef071b21cc4148779316f74ee924f15a'
        } else if (this.ticket.split(',')[0] === '机关(服务)') {
          this.permissions = '97fd6ee50f7c450eb52c90c0a5fec7c3'
        } else {
          if (this.ticket.split(',')[2] !== ' ') {
            if (this.ticket.split(',')[2] === '教学') {
              this.permissions = 'd2862a4ccc1f476396013cec88d76295'
            } else if (this.ticket.split(',')[2] === '教辅') {
              this.permissions = 'b23f784d3b014ffab668f11ec133368f'
            } else if (this.ticket.split(',')[2] === '机关') {
              this.permissions = '2f5b4d568be04501a08833e4e0764eae'
            }
          }
        }
      },
      // 考核账号
      createCounts () {
       if (this.count !== undefined && !isNaN(this.count) && this.ticket !== undefined && this.ticket !== '') {
          this.createCountAlert(Math.ceil((this.count - 0) * 1.2))
          this.createData = []
          this.counts = []
          this.redisData = []
          var randomArr = []
          if (this.count !== undefined && this.count !== null) {
            var accounts = Math.ceil((this.count - 0) * 1.2)
            this.$http({
              url: '/peopleinformation/checktime/checkTime/list',
              method: 'get',
              params: {
                'pageSize': 9999,
                'remarks': '人员'
              }
            }).then(({data}) => {
              if (data && data.success) {
                if (data.page.list[0] !== undefined) {
                 var timeYear = data.page.list[0].time.split('-')[0]
                 var timeCount = data.page.list[0].time.split('-')[1]
                  this.$http({
                    url: '/peopleinformation/peopleassessaccount/peopleAssessAccount/list',
                    method: 'get',
                    params: {
                      'pageSize': 9999,
                      'ticket': this.ticket.split(',')[0]
                    }
                  }).then(({data}) => {
                    if (data && data.success) {
                      for (let index = Number(data.page.count); index < (accounts + Number(data.page.count)); index++) {
                          this.isCountPermissions()
                          var k = Math.random() * 10000
                          for (var i = 0; i < randomArr.length; i++) {
                            if (randomArr[i] === k) {
                              k = Math.random() * 10000
                              i = 0
                            }
                            if (randomArr.length === i + 1) {
                              randomArr.push(k)
                            }
                          }
                          var val = ''
                          if (Math.floor(k).toString().length === 1) {
                            val = '000' + Math.floor(k)
                          } else if (Math.floor(k).toString().length === 2) {
                            val = '00' + Math.floor(k)
                          } else if (Math.floor(k).toString().length === 3) {
                            val = '0' + Math.floor(k)
                          } else {
                            val = Math.floor(k)
                          }
                          this.createData.push({
                            account: timeYear + '' + timeCount + this.ticket.split(',')[1] + (index < 100 ? '0' + (index < 10 ? '0' + index : index) : index) + val,
                            ticket: this.ticket.split(',')[0],
                            finishState: '未完成',
                            ticketCount: timeYear + '-' + timeCount
                          })
                          this.redisData.push({
                            key: this.createData[this.createData.length - 1].account + 'state',
                            value: '未填写'
                          })
                          this.counts.push({
                            loginName: timeYear + '' + timeCount + this.ticket.split(',')[1] + (index < 100 ? '0' + (index < 10 ? '0' + index : index) : index) + val,
                            newPassword: 0,
                            confirmNewPassword: 0,
                            loginFlag: '1',
                            company: {
                              id: '2f0a0b8d0b2745bab97c4c13cedd59af',
                              name: ''
                            },
                            name: this.ticket.split(',')[0],
                            office: {
                              id: '8e23c1a51d214f13943e3555fd0baab0',
                              name: ''
                            },
                            roleIdList: this.permissions,
                            ticketCount: timeYear + '-' + timeCount
                          })
                        if ((accounts + Number(data.page.count)) - 1 === index) {
                          this.$refs.asynForTool.func('/peopleinformation/peopleassessaccount/peopleAssessAccount/save', 'post', this.createData)
                          this.$refs.asynForTool.func('/sys/user/save', 'post', this.counts)
                          this.$refs.asynForTool.func('/peopleinformation/administrativelevel/peopleAdministrativeLevel/Redisset', 'post', this.redisData)
                        }
                      }
                    }
                  })
            }
           }
          })
          }
       }
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageNo = 1
        this.refreshList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageNo = val
        this.refreshList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },

    // 排序
      sortChangeHandle (obj) {
        if (obj.order === 'ascending') {
          this.orderBy = obj.prop + ' asc'
        } else if (obj.order === 'descending') {
          this.orderBy = obj.prop + ' desc'
        } else {
          this.orderBy = ''
        }
        this.refreshList()
      },
      // 新增
      add () {
        this.$refs.peopleAssessAccountForm.init('add', '')
      },
      // 修改
      edit (id) {
        id = id || this.dataListSelections.map(item => {
          return item.id
        })[0]
        this.$refs.peopleAssessAccountForm.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.peopleAssessAccountForm.init('view', id)
      },
      // 删除
      del (id) {
        let ids = id || this.dataListSelections.map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.$http({
            url: '/peopleinformation/peopleassessaccount/peopleAssessAccount/delete',
            method: 'delete',
            params: {'ids': ids}
          }).then(({data}) => {
            if (data && data.success) {
              this.$message.success(data.msg)
              this.refreshList()
            }
            this.loading = false
          })
        })
      },
      // 导入成功
      uploadSuccess (res, file) {
        if (res.success) {
          this.$message.success({dangerouslyUseHTMLString: true,
            message: res.msg})
        } else {
          this.$message.error(res.msg)
        }
      },
      // 下载模板
      downloadTpl () {
        this.$utils.download('/peopleinformation/peopleassessaccount/peopleAssessAccount/import/template')
      },
      exportExcel () {
        let params = {
          ...this.searchForm
        }
        this.$utils.download('/peopleinformation/peopleassessaccount/peopleAssessAccount/export', params)
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      }
    }
  }
</script>
